/*
 * package core: Browser, Dom, Ajax, Json, Animation
 */

if(typeof jav == 'undefined' || !jav){
	var jav = {};
}
jav.namespase = function(){
	var a = arguments, o = null, i, j, d;
	for(i=0; i<a.length; ++i){
		d = a[i].split('.');
		o = jav;
		for(j=(d[0]=='jav') ? 1 : 0; j<d.length; ++j){
			o[d[j]] = o[d[j]] || {};
			o = o[d[j]];
		}
	}
	return o;
};

(function(){
	var D = jav.dom, 
		reClassNameCache={},
		
		//dom aliases
		document = window.document,
		documentElement = window.documentElement,
		
		//string constants
		OWNER_DOCUMENT = 'ownerDocument',
		COMPAT_MODE = 'compatMode',
		OFFSET_LEFT = 'offsetLeft',
        OFFSET_TOP = 'offsetTop',
		CSS1_COMPAT = 'CSS1Compat',
        BACK_COMPAT = 'BackCompat',
		DOCUMENT_ELEMENT = 'documentElement',
		GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect',
		LEFT = 'left',
        TOP = 'top',
		GET_COMPUTED_STYLE = 'getComputedStyle',
		CURRENT_STYLE = 'currentStyle',
		BORDER_LEFT_WIDTH = 'borderLeftWidth',
	    BORDER_TOP_WIDTH = 'borderTopWidth',
	    NODE_TYPE = 'nodeType';
	
	var getClassRegEx = function(className){
		var re = reClassNameCache[className];
		if(!re){
			re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
			reClassNameCache[className] = re;
		}
		return re;
	}
	
/**
 * javascript language
 */
	jav.lang = {
		trim : function(s){
			try{
				return s.replace(/^\s+|s+$/g, '');
			}catch(e){
				return s;
			}
		}
	};
/**
 * event util
 */	
	jav.ev = {
		getTarget : function(ev, resolveTextNode){
			var oTag = ev.target || ev.srcElement;
			return this.resolveTextNode(oTag);
		},
		resolveTextNode : function(oTag){
			try{
				if(oTag && oTag.nodeType == 3){
					return oTag.parentNode;
				}
			}catch(e){}
			return oTag;
		},
		addEventHandler : function(oTag, sEType, fn){
			if(oTag.addEventListener){
				oTag.addEventListener(sEType, fn, false);
			}else if(oTag.attachEvent){
				oTag.attachEvent('on'+sEType, fn);
			}else{
				return function(){};
			}
		},
		removeEventHandler : function(){
			if(window.removeEventListener){
				return function(oTag, sEType, fn){
					oTag.removeEventListener(sEType, fn, false);
				};
			}else if(window.detachEvent){
				return function(oTag, sEType, fn){
					oTag.detachEvent('on'+sEType, fn);
				};
			}else{
				return function(){};
			}
		}()
	};
	
/**
 * dom util
 */	
	var _testElement = function(node){
		return node && node[NODE_TYPE] == 1;
	};
	jav.dom = {
		getId : function(el){
			if(el){
				if(el.nodeType || el.item){
					return el;
				}
				if(typeof el==='string'){
					return document.getElementById(el);
				}
				if('length' in el){
					var c = [];
					for(var i=0,len=el.length; i<len; i++){
						c[c.length]=jav.dom.getId(el[i]);
					}
					return c;
				}
				return el;
			}
			return null;
		},
		getClass : function(className, tag, root){
			className = jav.lang.trim(className);
			tag = tag || '*';
			root = (root) ? D.gId(root) : null || document;
			if(!root){
				return [];
			}
			
			var nodes = [], 
				elements=document.getElementsByTagName(tag),
				re = getClassRegEx(className);
			
			for(var i=0, len=elements.length; i<len; i++){
				if(re.test(elements[i].className)){
					nodes[nodes.length]=elements[i];
				}
			}
			return nodes;
		},
		hasClass : function(){
			
		},
		removeClass : function(){
			
		},
		setStyles : function(el, oStyle){
			
		},
		getXY : function(){
			if(document[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]){
				return function(node){
					var scrollLeft, scrollTop, box, doc,
						off1, off2, mode, bLeft, bTop,
						floor = Math.floor,
						xy = false;
					
					box = node[GET_BOUNDING_CLIENT_RECT]();
					doc = node[OWNER_DOCUMENT];
					
					scrollLeft = this.getDocumentScrollLeft(doc);
					scrollTop = this.getDocumentScrollTop(doc);
					xy = [floor(box[LEFT]), floor(box[TOP])];
					
					if(scrollLeft || scrollTop){
						xy[0] += scrollLeft;
						xy[1] += scrollTop;
					}
					
					xy[0] = floor(xy[0]);
					xy[1] = floor(xy[1]);
					return xy;
				}
			}else{
				return function(node){
					var docScrollTop, docScrollLeft, doc,
						scrollTop, scrollLeft,
						floor = Match.floor,
						xy = false;
					
					doc = node[OWNER_DOCUMENT];
					
					docScrollTop = this.getDocumentScrollLeft(doc);
					docScrollLeft = this.getDocumentScrollTop(doc);
					xy = [node[OFFSET_LEFT], node[OFFSET_TOP]];
					
					if(scrollLeft || scrollTop){
						xy[0] += scrollLeft;
						xy[1] += scrollTop;
					}
					
					xy[0] = floor(xy[0]);
					xy[1] = floor(xy[1]);
					return xy;
				}
			}
		}(),
		getDocumentScrollLeft : function(doc){
			doc = doc || document;
			return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft);
		},
		getDocumentScrollTop : function(doc){
			doc = doc || document;
			return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop);
		},
		getChildren : function(el){
			el = this.getId(el);
			var children = el.childNodes, len = children.length, newChildren = [];
			for(var i=0; i<len; i++){
				if(_testElement(children[i])){
					newChildren[newChildren.length] = children[i];
				}
			}
			return newChildren;
		},
		getNextSiblingBy : function(el){
			while(el){
				el = el.nextSibling;
				if(_testElement(el)){
					return el;
				}
			}
			return null;
		},
		isAncestor : function(haystack, needle){
			var haystack = this.getId(haystack);
			var needle = this.getId(needle);
			
			var ret = false;
			
			if( (haystack && needle) && (haystack['nodeType'] && needle['nodeType']) ){
				if (haystack.contains && haystack !== needle) {
                    ret = haystack.contains(needle);
                }
                else if (haystack.compareDocumentPosition) {
                    ret = !!(haystack.compareDocumentPosition(needle) & 16);
                }
			}else{}
			return ret;
		}
	};
	
})();
/**
 * ajax util
 */
var AJAX = (function(){
	function handleReadyState(o, callback){
		var poll = window.setInterval(
			function(){
				if(o && o.readyState === 4){
					window.clearInterval(poll);
					if(callback){
						callback(o);
					}
				}
			},50
		);
	};
	var getXHR = function(){
		var xhr,
			msxml = [
		                'MSXML2.XMLHTTP.5.0',
		                'MSXML2.XMLHTTP.4.0',
		                'MSXML2.XMLHTTP.3.0',
		                'MSXML2.XMLHTTP',
		                'Microsoft.XMLHTTP'
		                ];
;
		try{
			xhr = new XMLHttpRequest();
			getXHR = function(){
				return new XMLHttpRequest;
			}
		}catch(e){
			for(var i=0, len=msxml.length; i<len; i++){
				try{
					xhr = new ActiveXObject(msxml[i]);
					getXHR = function(){
						return new ActiveXObject(msxml[i]);
					}
					break;
				}catch(e){}
			}
		}
		return xhr;
	};
	
	return function(method, uri, callback, postData){
		var xhr = getXHR();
		xhr.open(method, uri, true);
		handleReadyState(xhr, callback);
		xhr.send(postData || null);
		return xhr;
	};
})();

var D = jav.dom, E = jav.ev;
	E.on = E.addEventHandler;
	G = D.getId ;

jav.namespase('effect');
/**
 * tab	accordion  
 */
jav.effect = (function(){
	
	return {
		tab : function(Obj){
			var oLis = D.getChildren(Obj.navId),oLisLen = oLis.length, aAs = [], aRelDivs = [];
			for(var i = 0; i<oLisLen; i++){
				var oA = D.getChildren(oLis[i])[0];
				aAs[aAs.length]=oA;
				aRelDivs[aRelDivs.length]=oA.rel;
			}
			
			//yui 中event.on的价值，渐渐理解了它 的源码，对多个元素统一事件类型，支持事件类型兼容性
			
			for(var i = 0; i<oLisLen; i++){
				aAs[i].onclick = function(){
					for(var i=0; i<oLisLen; i++){
						if(this.parentNode==oLis[i] && this.rel==aRelDivs[i]){
							oLis[i].className = 'cur';
							G(aRelDivs[i]).style.display = 'block';
						}else{
							oLis[i].className = '';
							G(aRelDivs[i]).style.display = 'none';
						}
					}
				};
			}
		},
		shrinkMenu : function(Obj){
			//console.log(D.getClass(Obj.onOff));
			//var articles = D.getChildren(Obj.ink);
			//alert(D.getChildren(articles[0])[1].className);
			var onOffs = D.getClass(Obj.onOff), len = onOffs.length;
			for(var i=0; i<len; i++){
				onOffs[i].onclick = function(){
					var controlItem = this.parentNode.parentNode;
					if(controlItem.className=='chapter'){
						controlItem.className = 'chapter hide';
						this.className = 'option turn-off';
					}else{
						controlItem.className = 'chapter';
						this.className = 'option';
					}
				};
			}
		}
	};
	
})();
	
/**
 * JSON
 */
	
if (!this.JSON) {
    JSON = {};
}
(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {


        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {


        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];


        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }



        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':


            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':


            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }


            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }


    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {


            var i;
            gap = '';
            indent = '';

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }


            } else if (typeof space === 'string') {
                indent = space;
            }


            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }


            return str('', {'': value});
        };
    }


    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

            var j;

            function walk(holder, key) {

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                j = eval('(' + text + ')');

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

            throw new SyntaxError('JSON.parse');
        };
    }
}());